// 导入interact.js中的函数
window.serverUrl = "http://localhost:4000";

function forgotman() {//忘记密码
    alert('请发送“忘记密码”至邮箱1234567896325@whu.edu.cn进行密码重置');
  }
 
function login() {//登录
    //获取输入框的值
    var password = document.querySelector('#passwordInput');
    var username = document.querySelector('#usernameInput');
    //将输入信息传递给后台进行验证
    fetch(window.serverUrl+"/login", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: username.value,
          password: password.value
        })
      })
     .then(response => response.json())
     .then(data => {
        console.log(data);
        alert(data.msg);
        if(data.code==200){
          var token = data.data.token;
          dispname=data.data.username;
          var userrole=data.data.userrole;
          localStorage.setItem("ourtoken",token);
          localStorage.setItem("ourusername",dispname);//用于在界面上显示，可能需要
          localStorage.setItem("ouruserid",data.data.user_id);
          if(userrole==1){
            userrole="动物爱好者";}
          else if(userrole==2){
            userrole="专家用户";}
          else if(userrole==3){
            userrole="管理员";}
          else{
            userrole="未知用户";}
          localStorage.setItem("ouruserrole",userrole);
          if(token){window.location.href="index.html";}
        }
      })
     .catch(error => console.error(error));
    // interactLogin(username.value, password.value);
    loginButton = document.getElementById('loginButton');
    loginButton.disabled = true; // 禁用登录按钮，防止重复点击
}

function register() {//登录
    //获取输入框的值
    var password_para = document.querySelector('#passwordInput');
    var username_para = document.querySelector('#usernameInput');
    var userrole_para = document.querySelector('#roleSelect');
    //将用户输入信息进行格式转化
    console.log(userrole_para.value);
    if(userrole_para.value=="amateur"){
        userrole=1;}
    else if(userrole_para.value=="expert"){
        userrole=2;}
    else if(userrole_para.value=="admin"){
        userrole=3;}
    //将输入信息传递给后台进行验证
    var username=username_para.value;
    var password=password_para.value;
    console.log("开始向服务器发送注册请求");
    fetch(window.serverUrl+"/register", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: username,
          password: password,
          role:userrole
        })
      })
     .then(response => response.json())
     .then(data => {
        console.log(data);
        alert(data.msg);
        if(data.code==200){
          window.location.href="login.html";
        }
      })
     .catch(error => console.error(error));
    registerButton = document.getElementById('registerButton');
    registerButton.disabled = true; // 禁用注册按钮，防止重复点击

}




//交互函数
function interactLogin(username, password){
    console.log("Logging in with username: " + username + " and password: " + password);
    var xmlhttp;
    xmlhttp = null;
  
    //浏览器类型判断
    if (window.XMLHttpRequest)
        {//code for Firefox , Opera ,IE7, etc.
        xmlhttp= new XMLHttpRequest();
        }
    else if (window.ActivexObject)
        {//code for IE6,IE5
        xmlhttp= new ActivexObject("Microsoft.XMLHTTp");
        }
    //发出请求
    url=window.serverUrl+"/login";
    xmlhttp.open("POST",url,true);
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    const name = username;
    const pass = password;
    // 将用户名和密码封装成一个对象
    const data = {
            "username": name,
            "password": pass
    };
    // 将data对象转换为JSON字符串
    const dataString = JSON.stringify(data);
    xmlhttp.send(dataString);
    console.log(dataString);
    xmlhttp.onreadystatechange = state_Change;
    
    //处理服务器返回的数据
    function state_Change()
    {
    if (xmlhttp.readyState==4)
        {//4="loaded"
        if (xmlhttp.status==200)
            {//200="ok"
            console.log(xmlhttp.responseText);
             //将服务器返回的数据存在localStorage中，以便下次直接从localStorage中获取数据
            //解析json
            const jsonData = JSON.parse(xmlhttp.responseText);
            token=jsonData.data.token;
            dispname=jsonData.data.username;
            userrole=jsonData.data.userrole;  
            if(userrole==1){
              userrole="动物爱好者";}
            else if(userrole==2){
              userrole="专家";}
            else if(userrole==3){
              userrole="管理员";}
            else{
              userrole="未知用户";}
            localStorage.setItem("ourtoken",token);
            localStorage.setItem("ourusername",dispname);//用于在界面上显示，可能需要
            localStorage.setItem("ouruserrole",userrole);
            msg=jsonData.msg;
            code=jsonData.code;
            alert(msg);
              //跳转到主页
            if(token){window.location.href="index.html";}
            }
           
        else
            {
            const jsonData = JSON.parse(xmlhttp.responseText);
            msg=jsonData.msg;
            code=jsonData.code;
            alert(msg);
            return code;
            }    
        }
    }
} 

       


function interactRegister(username, password,userrole){
    console.log("Registering with username: " + username + " and password: " + password);
    var xmlhttp;
    xmlhttp = null;
  
    //浏览器类型判断
    if (window.XMLHttpRequest) 
        {//code for Firefox , Opera ,IE7, etc.
          xmlhttp= new XMLHttpRequest();
        }
    else if (window.ActivexObject)
        {//code for IE6,IE5
          xmlhttp= new ActivexObject("Microsoft.XMLHTTp");
        }
    //发出请求
    url=window.serverUrl+"/register";
    xmlhttp.open("POST",url,true);
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    const name = username;
    const pass = password;
    const role=userrole;
    // 将用户名和密码封装成一个对象
    const data = {
            "username": name,
            "password": pass,
            "role":role
    };
    // 将data对象转换为JSON字符串
    const dataString = JSON.stringify(data);
    xmlhttp.send(dataString);
    console.log(dataString);
    xmlhttp.onreadystatechange = state_Change;
    
   
     //处理服务器返回的数据
    function state_Change()
    {
    if (xmlhttp.readyState==4)
        {//4="loaded"
        if (xmlhttp.status==200)
            {//200="ok"
                console.log(xmlhttp.responseText);
                //解析json
                const jsonData = JSON.parse(xmlhttp.responseText);
               msg=jsonData.msg;
               alert(msg);
            window.location.href="login.html";
        }
        else
            {
            //解析json
            const jsonData = JSON.parse(xmlhttp.responseText);
            msg=jsonData.msg;
            code=jsonData.code;
            alert(msg);
            return code;
            }
        }   
        // 启用注册按钮
        var registerButton = document.getElementById('registerButton');
        registerButton.disabled = false;
    }

}


